import redis.asyncio as redis
from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise

from app.core.config import get_settings, CoreSettings
from app.core.tortoise_config import TORTOISE_ORM_CONFIG

settings: CoreSettings = get_settings()


class RedisPool:
    """redis pool"""
    _pool = None

    @classmethod
    async def get_redis(cls) -> redis.Redis:
        """ 获取redis连接 """
        if cls._pool is None:
            cls._pool = redis.ConnectionPool(
                host=settings.redis.host,
                port=settings.redis.port,
                db=settings.redis.db,
                password=settings.redis.password,
                max_connections=settings.redis.pool_size,
                decode_responses=True
            )
        return redis.Redis(connection_pool=cls._pool)

    @classmethod
    async def close(cls):
        """ 关闭连接池  """
        if cls._pool:
            await cls._pool.disconnect()


async def redis_provider():
    """redis"""
    return await RedisPool.get_redis()


def register_tortoise_orm(app: FastAPI):
    """
    注册tortoise orm
    :param app:
    """
    register_tortoise(
        app,
        config=TORTOISE_ORM_CONFIG,
        generate_schemas=True,
        add_exception_handlers=True,
    )
